package com.jian.mygame;

import java.util.ArrayList;

import org.jbox2d.common.Vec2;

import com.jian.mygame.MultiTouchHandler.MultiTouchEvent;
import com.jian.mygame.MyFactory;
import com.jian.mygame.R;
import com.jian.mygame.MultiTouchHandler.MyTouchEvent;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;


class MyToolBox extends Object {
    static final int LEFT_ACTION = 1;
    static final int RIGHT_ACTION = 2;
    private GameHandler mGameHandler = null;
    class MyAction {
	    private float PosX;
	    private float PosY;
	    
	    public float CenterPosX;
	    public float CenterPosY;
	    
	    private float Angle;
	    
	    public static final int DRAG_STATE_INIT = 0;
	    public static final int DRAG_STATE_MOVE = 1;
	    public static final int DRAG_STATE_UP = 2;
	    public static final int DRAG_STATE_DOWN = 3;
	    private int DragState = DRAG_STATE_INIT;
	    
	    Drawable[] mGun;
	    int mBulletType;
	    int mActionDirection;

	    boolean mLimitAngle;
	    float mMinAngle;
	    float mMaxAngle;
	    boolean mRevertAngle;
	    
	    boolean mActive;
	    String mStrPrefix;
	    
	    public MyAction(){
	    	mActive = false;
	    	mStrPrefix = "";
	    }
	    
	    private float prev_x = -1f;
	    private float prev_y = -1f;
	    private ArrayList<Vec2> mVec=new ArrayList<Vec2>(); 
		private void onTouch(){
			
			Log.d("TouchEvent", "state: " + DragState + " " + prev_x + " " + prev_y + " " + PosX + " " + PosY );
			switch(DragState){
			case DRAG_STATE_DOWN:
				prev_x = PosX;
				prev_y = PosY;
				mVec.clear();
				mVec.add(new Vec2(PosX, PosY));
				break;
			case DRAG_STATE_MOVE:
//				if( prev_x > 0 && prev_y > 0) {
//					Log.d("TouchEvent", prev_x + " " + prev_y + " " + PosX + " " + PosY );
//					//mGameHandler.CreateWall(prev_x, prev_y, PosX, PosY);
//				}
//				prev_x = PosX;
//				prev_y = PosY;
				//if( Math.abs(prev_x-PosX)>30 || Math.abs(prev_y-PosY)>30){
					mVec.add(new Vec2(PosX, PosY));
					prev_x = PosX;
					prev_y = PosY;
				//}
				break;
			case DRAG_STATE_UP:
				DragState = MyAction.DRAG_STATE_INIT;
		        prev_x = -1f;
			    prev_y = -1f;
			    //Add the 1st vertex to the the last position again
			    //mVec.add(mVec.get(0).clone());
			    Vec2[] vec = new Vec2[mVec.size()];
			    mVec.toArray(vec);
			    for(Vec2 v: vec){
			    	Log.d("MyWorld", "  vec[] x: " + v.x + " /y: " + v.y );
			    }
			    mGameHandler.AddPolygonObject(vec);
			    
				break;
				
			default:
				break;
			}
			
		}
	    /*
		private void drawWeapon( Canvas canvas ){
			//Draw Bullet
			float angle;
			int imageIdx = 0;
			
			angle = calcAngle();
			
			Angle = angle;
			switch(DragState){
			case DRAG_STATE_MOVE:
				//drawDrag( canvas, myAction );
				break;
			case DRAG_STATE_UP:
				//Random rnd = new Random();
		        //int num = rnd.nextInt(100);
		        
		        DragState = MyAction.DRAG_STATE_INIT;
				
		        
				GameHandler.mWorld.fire(CenterPosX, CenterPosY, 
									    new Vec2((float)(20*6000.0f*Math.cos(angle)),
									    		 (float)(20*6000.0f*Math.sin(angle)) 
									             ), 
									    angle,
									    mBulletType);
				
				break;
			default:
				break;
			}
			
			if( mGun.length > 1 ) {
				if( mRevertAngle){
					//Revert angle, since the direction of Picture is to left
					angle -= Math.PI; 
					angle = changeAngleRange( angle );
					angle = (float) Math.max( Math.min(angle, mMaxAngle),  mMinAngle);
				}
				//Use original image to show angle
				imageIdx = (int)(Math.abs( (angle - mMinAngle)/ ((mMaxAngle - mMinAngle )/(mGun.length-1) ) ) );
				angle = 0;
			}
			
			//Draw big gun
			GameHandler.drawBox(canvas, CenterPosX, CenterPosY, angle, mGun[imageIdx]);
			
			//For Debug
			drawDrag( canvas );
			
			//return myAction.DragState;
		}
		*/
		
		/*
		* Range from: -PI(-180C) -> PI(-180C) clockwise
		*/
		private float calcAngle() {
			float angle = 0.0f;

			//Calculate angle based on the current position 
//			if( PosX-CenterPosX > 0 ) {
//				angle = (float) (Math.atan((PosY-CenterPosY)/(PosX-CenterPosX)));
//				if( angle < 0 ) {
//					angle += Math.PI*2; //+2PI to make the negative angle become positive
//				}
//			} else {
//				angle = (float) (Math.atan((PosY-CenterPosY)/(PosX-CenterPosX))+Math.PI);
//			}
			angle = MyUtil.calculateAngle( (PosX-CenterPosX), (PosY-CenterPosY) );

			//Change angle range to within 0->2PI
			angle = MyUtil.changeAngleRange( angle );

			//Revert angle, since we want to drag the rear of the object to change its angle
			angle = (float)(angle - Math.PI);
			angle = MyUtil.changeAngleRange( angle );
			
			//limite weapon range
			if( mLimitAngle ) {
				angle = (float) Math.max( Math.min(angle, mMaxAngle),  mMinAngle);
			}
			
			return angle;
		}

		
		private void drawDrag(Canvas canvas){
			MyPainter.drawLine(canvas, PosX, PosY, CenterPosX, CenterPosY);
		}
		
		private void drawDebug(Canvas canvas ){
			MyPainter.drawText(canvas, 200, 30, Color.BLUE, Color.BLACK, "Angle: " + String.valueOf(Angle));
		}

		boolean analyzeAction( MyTouchEvent mev ){
			boolean bhandled = false;
			//MyAction myAction = new MyAction();
			String strPrefix="";
			
			if(mActionDirection==LEFT_ACTION){
				strPrefix = "LEFT: ";
			} else if(mActionDirection==RIGHT_ACTION){
				strPrefix = "RIGHT: ";
			}
			
			switch (mev.getAction()) {
			case MotionEvent.ACTION_DOWN:
				//if( OnActionDown(mev.getX(), mev.getY()) ) {
					mActive = true;
					PosX = mev.getX();
					PosY = mev.getY();
					DragState = MyAction.DRAG_STATE_DOWN;
				//}
				Log.d("TouchEvent", strPrefix + "ACTION_DOWN");
				bhandled = true;
				break;
			case MotionEvent.ACTION_UP:
				if( mActive ) {
					mActive = false;
					PosX = mev.getX();
					PosY = mev.getY();
					DragState = MyAction.DRAG_STATE_UP;
					Log.d("TouchEvent", strPrefix + "ACTION_UP");
				}
				bhandled = true;
				break;
			case MotionEvent.ACTION_MOVE:
				if( mActive ){
					PosX = mev.getX();
					PosY = mev.getY();
					DragState = MyAction.DRAG_STATE_MOVE;
					Log.d("TouchEvent", strPrefix + "ACTION_MOVE" + " X: " + PosX + " Y: " + PosY );
					Log.d("TouchEvent", "Before state: " + DragState + " " + prev_x + " " + prev_y + " " + PosX + " " + PosY );
				}
				bhandled = true;
				break;
			case MotionEvent.ACTION_CANCEL:
				Log.d("TouchEvent", strPrefix + "ACTION_CANCEL");
				bhandled = true;
				break;
			default:
				break;
			}
			
			return (bhandled);
		}
		
		boolean OnActionDown( float x, float y ) {
			boolean bActivated = false;
			float halfwidth = mGun[0].getIntrinsicWidth()/2;
			float halfheight = mGun[0].getIntrinsicHeight()/2;
			
			if( ((CenterPosX - halfwidth) <= x) && 
				((CenterPosX + halfwidth) >= x) && 
				((CenterPosY - halfheight) <= y) && 
				((CenterPosY + halfheight) >= y) ){
				bActivated = true;
			}
			
			return (bActivated);
		}
	    
    };
    MyAction mLeftAction, mRightAction;
	
	public MyToolBox( Context context, GameHandler GameHandler ){
        Resources res = context.getResources();
        
        mGameHandler = GameHandler;
        
        mLeftAction = new MyAction();
        mLeftAction.CenterPosX = 120;
        mLeftAction.CenterPosY = 220;
        mLeftAction.PosX = 60;
        mLeftAction.PosY = 220;
        mLeftAction.mLimitAngle = false;
        mLeftAction.mGun = new Drawable[1];
        mLeftAction.mGun[0] = res.getDrawable(R.drawable.blackgun_s);
        mLeftAction.mRevertAngle = false;
        mLeftAction.mBulletType = MyFactory.BULLET_TYPE0;
        mLeftAction.mActionDirection = LEFT_ACTION;
        
        mRightAction = new MyAction();
        mRightAction.CenterPosX = 400;
        mRightAction.CenterPosY = 220;
        mRightAction.PosX = 460;
        mRightAction.PosY = 220;
        mRightAction.mLimitAngle = true;
        mRightAction.mMinAngle = (float)(0.0f);
        mRightAction.mMaxAngle = (float)(Math.PI/6);
        mRightAction.mGun = new Drawable[12];
        mRightAction.mGun[0] = res.getDrawable(R.drawable.biggun0);
        mRightAction.mGun[1] = res.getDrawable(R.drawable.biggun1);
        mRightAction.mGun[2] = res.getDrawable(R.drawable.biggun2);
        mRightAction.mGun[3] = res.getDrawable(R.drawable.biggun3);
        mRightAction.mGun[4] = res.getDrawable(R.drawable.biggun4);
        mRightAction.mGun[5] = res.getDrawable(R.drawable.biggun5);
        mRightAction.mGun[6] = res.getDrawable(R.drawable.biggun6);
        mRightAction.mGun[7] = res.getDrawable(R.drawable.biggun7);
        mRightAction.mGun[8] = res.getDrawable(R.drawable.biggun8);
        mRightAction.mGun[9] = res.getDrawable(R.drawable.biggun9);
        mRightAction.mGun[10] = res.getDrawable(R.drawable.biggun10);
        mRightAction.mGun[11] = res.getDrawable(R.drawable.biggun11);
        mRightAction.mRevertAngle = true;
        mRightAction.mBulletType = MyFactory.BULLET_TYPE0;
        mRightAction.mActionDirection = RIGHT_ACTION;
        
	}
	
	boolean onTouchEvent( MultiTouchEvent mtv ){
    	boolean bhandled = false;
    	
    	if( mtv.has_left_ev) {
    		bhandled = mLeftAction.analyzeAction(mtv.left_ev);
    		mLeftAction.onTouch();
    	}
    	
    	if( mtv.has_right_ev) {
    		bhandled = mRightAction.analyzeAction(mtv.right_ev);
    	}
    	
    	return (bhandled);
	}
	
	public void drawTools( Canvas canvas ) {
		//For debug
		//mLeftAction.drawDrag( canvas);
	}
	
	/*
	public void drawWeapon( Canvas canvas ) {
		//Draw weapon
		mLeftAction.drawWeapon(canvas);
		mRightAction.drawWeapon(canvas);
		
		//Draw Debug Info
		mLeftAction.drawDebug(canvas);
		//drawDebug(canvas,mRightAction);
	}
	*/
}
